<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList" />
    <!-- 主体部分 -->
    <TodoBody
      :list="renderList"
      :isCheckAll="isCheckAll"
      @delList="delList"
      @changeStatus="changeStatus"
      @changeChecked="changeChecked"
    />
    <!-- 底部部分 -->
    <TodoFooter
      :leftListLength="leftListLength"
      :isDoneAll="isDoneAll"
      v-model="type"
      @clearDoneList="clearDoneList"
      v-show="list.length"
    />
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'

export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  //定义数据
  data() {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('TodoList')) || [],
    }
  },

  //方法集合
  methods: {
    //删除事件
    delList(id) {
      //筛选不是同一个id的项，做到删除的效果
      this.list = this.list.filter((item) => item.id !== id)
    },

    //修改状态事件
    changeStatus(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },

    //添加事件
    addList(value) {
      const obj = { id: +new Date(), name: value, isDone: false }

      this.list = [obj, ...this.list]
    },

    //清除所有已完成的事件
    clearDoneList() {
      this.list = this.list.filter((item) => !item.isDone)
    },

    //修改type
    changeType(type) {
      this.type = type
    },

    //修改所有的多选框状态
    changeChecked(flag) {
      this.list.forEach((item) => (item.isDone = flag))
    },
  },

  //计算属性
  computed: {
    //剩余未完成事件的长度
    leftListLength() {
      return this.list.filter((item) => !item.isDone).length
    },
    //是否显示清除已完成的按钮
    isDoneAll() {
      return this.list.some((item) => item.isDone)
    },
    //根据不同的type类型展示不同的数据
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.isDone)
        case 'completed':
          return this.list.filter((item) => item.isDone)
        default:
          return this.list
      }
    },

    //设置全选属性
    isCheckAll() {
      return this.list.every((item) => item.isDone)
    },
  },

  //监听属性
  watch: {
    list: {
      deep: true,
      handler(value) {
        //存储到本地
        localStorage.setItem('TodoList', JSON.stringify(value))
      },
    },
  },
}
</script>

<style></style>
